package com.czkevin.cifjiaocheng.cif;

import de.tr7zw.nbtapi.NBTCompound;
import com.czkevin.cifaddon.blockentity.BaseBlockWithEntity;
import com.czkevin.cifaddon.blockentity.CustomBlockEntity;
import com.czkevin.cif.CIFItemInstance;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.ArmorStand;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.util.EulerAngle;

public class Toilet extends BaseBlockWithEntity {
    @Override
    public String getDisplayName(NBTCompound nbtCompound) {
        return "\u00a7d\u00a7l撤硕";
    }

    @Override
    public Material getModelMaterial() {
        return Material.DIAMOND;
    }

    @Override
    public int getCustomModelData(CIFItemInstance instance) {
        return 85700;
    }

    @Override
    public CustomBlockEntity onLoad(CIFItemInstance cifItemInstance, Location location) {
        return new ToiletCoverEntity(location, cifItemInstance);
    }

    private static class ToiletCoverEntity extends CustomBlockEntity {
        private static final ItemStack TOILET_COVER = new ItemStack(Material.DIAMOND);
        static {
            ItemMeta meta = TOILET_COVER.getItemMeta();
            meta.setCustomModelData(85701);
            TOILET_COVER.setItemMeta(meta);
        }

        public ToiletCoverEntity(Location location, CIFItemInstance state) {
            super(location, state);
        }

        private ArmorStand headEntity;

        private static final double STEP = Math.toRadians(4);
        private static final double MAX = Math.toRadians(180);
        private static final double DEG90 = Math.toRadians(90);
        private double current;

        @Override
        public void doTick() {
            current = (current + STEP) % MAX;
            double sinResult = (Math.sin(current) + 1) / 2d * DEG90; // 0 - 90 之间
            headEntity.setHeadPose(
                new EulerAngle(-(sinResult*2), 0d, 0d)
            );
        }

        @Override
        public void initialize() {
            Location location = getLocation().add(.5d, -.5d, .1d);
            headEntity = location.getWorld()
                .spawn(
                    location, ArmorStand.class, (c) -> {
                        addPart(c);
                        c.setGravity(false);
                        c.setVisible(false);
                        c.setBasePlate(false);
                    }
                );
            headEntity.getEquipment().setHelmet(TOILET_COVER);
        }
    }
}
